package com.example.recyclerviewcontextmenudemo;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

import com.example.recyclerviewcontextmenudemo.dataoop.Book;

public class EditBookActivity extends AppCompatActivity {
    public static final String EXTRA_BOOK = "extra_book";
    public static final String EXTRA_RESULT_BOOK = "extra_result_book";

    private EditText etName;
    private EditText etPrice;
    private Book originalBook;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_book);

        etName = findViewById(R.id.et_name);
        etPrice = findViewById(R.id.et_price);
        Button btnSave = findViewById(R.id.btn_save);

        originalBook = getIntent().getParcelableExtra(EXTRA_BOOK);
        if (originalBook != null) {
            etName.setText(originalBook.getName());
            etPrice.setText(String.valueOf(originalBook.getPrice()));
        }

        btnSave.setOnClickListener(v -> {
            String bookName = etName.getText().toString().trim();
            double bookPrice = Double.parseDouble(etPrice.getText().toString().trim());

            Book resultBook;
            if (originalBook != null) {
                originalBook.setName(bookName);
                originalBook.setPrice(bookPrice);
                resultBook = originalBook;
            } else {
                resultBook = new Book(bookName, bookPrice);
            }

            Intent intent = new Intent();
            intent.putExtra(EXTRA_RESULT_BOOK, resultBook);
            setResult(RESULT_OK, intent);
            finish();
        });
    }
}